﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using YodaMaster.Models;
using System.Data.Entity;

namespace YodaMaster.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        SchoolContext db = new SchoolContext();
       // LoginContext DB = new LoginContext();

        public ActionResult Index()
        {
            Database.DefaultConnectionFactory = new System.Data.Entity.Infrastructure.SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

            MyCart cart = MyCart.GetCart(this.HttpContext);
            cart.EmptyCart();

            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                
                var item = (from c in db.Users where c.Username == model.Username && c.Password == model.Password select c);
                if (item.Count() > 0)
                {
                    var item2 = (from c in db.Students where c.StudentID == model.Username select c).Single();
                    var item3 = new ConnectedStudents()
                    {
                        FirstMidName = item2.FirstMidName,
                        LastName = item2.LastName,
                        StudentID = item2.StudentID,
                        studentType = item2.studentType
                    };

                    item3.Enrollments = new List<Enrollment>();
                    foreach(var item4 in item2.Enrollments)
                    {
                        item3.Enrollments.Add(item4);
                    }
                    db.Online_Users.Add(item3);
                    MyCart cart = MyCart.GetCart(this.HttpContext);

            

                    db.SaveChanges();
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    return RedirectToAction("Index", "Home");
                }
                {
               ModelState.AddModelError("", "Invalid Username or Password");
                }
            }
            return View();
        }

        public ActionResult MyProfile()
        {
            
                return View(db.Online_Users.ToList()[db.Online_Users.Count()-1]);
        }

        public ActionResult Logout()
        {
            
            string[] myCookies = Request.Cookies.AllKeys;
            foreach (string cookie in myCookies)
            {
                Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
            }
            Session.Clear();
            FormsAuthentication.SignOut();
            return View();
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
     

    }
}
